#!/usr/bin/env bash

mkdir /etc/apache2/ssl 2>/dev/null

PATH_SSL="/etc/apache2/ssl"
PATH_KEY="${PATH_SSL}/${1}.key"
PATH_CSR="${PATH_SSL}/${1}.csr"
PATH_CRT="${PATH_SSL}/${1}.crt"

if [ ! -f $PATH_KEY ] || [ ! -f $PATH_CSR ] || [ ! -f $PATH_CRT ]
then
  openssl genrsa -out "$PATH_KEY" 2048 2>/dev/null
  openssl req -new -key "$PATH_KEY" -out "$PATH_CSR" -subj "/CN=$1/O=Vagrant/C=UK" 2>/dev/null
  openssl x509 -req -days 365 -in "$PATH_CSR" -signkey "$PATH_KEY" -out "$PATH_CRT" 2>/dev/null
fi

rewrite=""
if [ "$7" -eq "1" ]
then

	rewrite="
<Directory $2>
<IfModule mod_rewrite.c>
  Options +FollowSymlinks
  RewriteEngine On

  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^(.*)$ $6/\$1 [QSA,PT,L]
</IfModule>
</Directory>
"

fi

block="<VirtualHost *:$3>

       ServerAdmin webmaster@localhost
       ServerName $1
       ServerAlias www.$1
       DocumentRoot $2

       ErrorLog ${APACHE_LOG_DIR}/error.log
       CustomLog ${APACHE_LOG_DIR}/access.log combined
	   <Directory $5>
		Options Indexes FollowSymLinks
		AllowOverride All
		require all granted
	</Directory>
	DirectoryIndex $6
	$rewrite
</VirtualHost>
"

echo "$block" > "/etc/apache2/sites-available/$1.conf"
ln -fs "/etc/apache2/sites-available/$1.conf" "/etc/apache2/sites-enabled/$1.conf"
